package com.dongdongshop.service.impl;

import com.dongdongshop.page.PageResult;
import com.dongdongshop.pojo.Conment;
import com.dongdongshop.service.ConmentService;
import com.dongdongshop.vo.ConmentVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.client.result.UpdateResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@DubboService
public class ConmentServbiceImpl implements ConmentService {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void addConment(ConmentVo conmentVo) {
        Conment conment = new Conment();
        BeanUtils.copyProperties(conmentVo,conment);
        mongoTemplate.save(conment);
    }

    @Override
    public PageResult<ConmentVo> findAll(Integer pageNum, Integer pageSize, String rank) {
        //条件查询
        Query query = null;
        if(rank == null || rank.equals("")){
            query = new Query();
        }else {
            query = new Query(Criteria.where("rank").is(Long.valueOf(rank)));
        }
        //得到总条数
        long count = mongoTemplate.count(query, Conment.class);
        //分页
        query.skip((pageNum - 1) * pageSize).limit(pageSize);
        Integer page = Math.toIntExact(count % pageSize == 0 ? count / pageSize : count / pageSize + 1);
        List<Conment> conments = mongoTemplate.find(query, Conment.class);
        List<ConmentVo> vos = new ArrayList<>();
        for (Conment conment : conments) {
            ConmentVo conmentVo = new ConmentVo();
            BeanUtils.copyProperties(conment,conmentVo);
            vos.add(conmentVo);
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo i = new PageInfo(vos);
        return new PageResult<>(pageNum,i.getPageSize(),count,page,i.getList());
    }

    @Override
    public void updataZanById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        List<Conment> conments = mongoTemplate.find(query, Conment.class);
        Conment conment = conments.get(0);
        Update update = new Update().set("zan",conment.getZan() + 1);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, Conment.class);

    }
}
